import { FC, memo, useState } from "react";
import { useNavigate } from "react-router-dom";
import { LockOutlined, MoonOutlined, SunOutlined, UserOutlined } from "@ant-design/icons";
import { App, Button, Checkbox, Divider, Form, Input, Switch, Tooltip } from "antd";
import classNames from "classnames";
import md5 from "js-md5";

import { getUserResource, IUserResourceResponse, login } from "@/api/auth";
import { SvgIcon } from "@/components/SvgIcon";
import { usePermissionStore, useSettingStore } from "@/store";
import { IBaseComponentProps } from "@/types/component";
import { setToken, setUserInfo } from "@/utils/auth";
import { transformListToTree } from "@/utils/transformListToTree";

// import variables from "@/styles/variables.module.scss";
import "./index.scss";

export interface ILoginProps extends IBaseComponentProps {}

const prefixcls = "login";

const Login: FC<ILoginProps> = memo((props) => {
  const { className } = props;

  const navigate: any = useNavigate();
  const { isDark, updateIsDark } = useSettingStore();
  const { updateResource, updateMenuList } = usePermissionStore();

  const { message } = App.useApp();

  const [loginForm] = Form.useForm();

  const [isCapslock, setIsCapslock] = useState(false);
  const [isLoading, setIsLoading] = useState(false);

  const transformMenu = (data: IUserResourceResponse[]) => {
    return data.map((item) => {
      const { authorityCode, resourceType, resourceName, children } = item;
      let menuItem: any = {};
      if (resourceType === "02") {
        menuItem = {
          key: authorityCode, // 路由路径
          label: resourceName, // 组件名称，用于 <router-view> 的名字匹配
          type: resourceType,
          children: transformMenu(children),
        };
      }

      if (resourceType === "03") {
        menuItem = {
          key: authorityCode, // 路由路径
          label: resourceName, // 组件名称，用于 <router-view> 的名字匹配
          type: resourceType,
          children: transformMenu(children),
        };
      }

      if (resourceType === "04") {
        menuItem = {
          key: authorityCode, // 路由路径
          label: resourceName, // 组件名称，用于 <router-view> 的名字匹配
          type: resourceType,
        };
      }

      return menuItem;
    });
  };

  /**
   * 检查CapsLock键是否被按下
   * @param e 事件对象
   */
  const checkCapslock = (e: any) => {
    if (e.key === "CapsLock") {
      setIsCapslock(e.getModifierState("CapsLock"));
    }
  };

  const handleLoginSubmit = async () => {
    loginForm
      .validateFields()
      .then((values) => {
        setIsLoading(true);
        login({ ...values, password: md5(values.password + "sticker") }).then(async (res) => {
          const { token, ...userInfo } = res;
          setToken(token);
          setUserInfo(userInfo);
          const userResource = await getUserResource();
          const data = transformListToTree(userResource.list);
          const menuList = transformMenu(data);
          updateMenuList(menuList);
          updateResource(userResource.list);
          navigate("/");
        });
      })
      .finally(() => {
        setIsLoading(false);
      });
  };

  return (
    <App>
      <div className={classNames(prefixcls, className)}>
        {/* 登录页头部 */}
        <div className="login-header">
          <Switch
            checkedChildren={<MoonOutlined />}
            unCheckedChildren={<SunOutlined />}
            value={isDark}
            onChange={updateIsDark}
          />
        </div>
        {/* 登录页内容 */}
        <div className="login-form">
          <Form form={loginForm} className="w-100%">
            <div className="form-title">
              <h2>贴纸机后台管理系统</h2>
            </div>
            <Form.Item
              name="userAccount"
              key="userAccount"
              rules={[{ required: true, message: "请输入用户名!" }]}
            >
              <Input
                size="large"
                placeholder="用户名"
                className="h-48px"
                prefix={<UserOutlined />}
              />
            </Form.Item>
            <Tooltip open={isCapslock} placement="right" title="大写已锁定">
              <Form.Item
                name="password"
                key="password"
                rules={[{ required: true, message: "请输入密码!" }]}
              >
                <Input.Password
                  size="large"
                  placeholder="密码"
                  className="h-48px"
                  prefix={<LockOutlined />}
                  onKeyUp={checkCapslock}
                />
              </Form.Item>
            </Tooltip>
            <div className="flex-x-between w-full py-1">
              <Checkbox>记住我</Checkbox>
              <a className="text-blue" onClick={() => message.info("请联系管理员！")}>
                忘记密码
              </a>
            </div>
            <Button
              type="primary"
              size="large"
              loading={isLoading}
              className="w-full"
              onClick={handleLoginSubmit}
            >
              登录
            </Button>
            <Divider plain>
              <div className="text-sm">其他登录方式</div>
            </Divider>
            <div className="third-party-login" onClick={() => message.warning("该功能暂未开放！")}>
              <SvgIcon iconClass="qq" />
              <SvgIcon iconClass="wechat" />
              <SvgIcon iconClass="github" />
              <SvgIcon iconClass="gitee" />
            </div>
          </Form>
        </div>
      </div>
    </App>
  );
});

export default Login;
